<?php
declare (strict_types=1);
namespace app\course\model\base;

use app\common\model\BaseModel;
use app\course\model\record\LearnCourseRecord;
use app\user\model\user\Account;
use think\model\relation\BelongsTo;
use think\model\relation\HasOne;

/**
 * 定义课程学员数据模型
 */
class CourseStudent extends BaseModel
{
    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'course_student';

    /**
     * 定义字段类型
     *
     * @var array
     */
    protected $type = [
        'id'        => 'integer',
        'user_id'   => 'integer',
        'course_id' => 'integer',
        'from'      => 'integer',
    ];

    protected static $fromText = [
        1 => '后台添加',
        2 => '学员购买',
        3 => '会员购买',
        4 => '免费课程加入',
        5 => '会员免费加入',
        6 => '课程卡兑换'
    ];

// 获取器

    public function getFromTextAttr($value, $data): string
    {
        return static::$fromText[$data['from']];
    }

    /**
     * 成功创建之后
     */
    public static function onAfterInsert($stu)
    {
        // 添加待通知记录
        StudentCourseNotify::create(['course_id' => $stu->course_id, 'user_id' => $stu->user_id]);
    }

//关联

    /**
     * 关联用户
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-30
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'user_id');
    }

    /**
     * 关联课程
     */
    public function course(): BelongsTo
    {
        return $this->belongsTo(Course::class, 'course_id')->with(['cover_url'])->bind([
            'course_title'     => 'title',
            'course_cover'     => 'cover_url',
            'course_type'      => 'course_type',
            'course_type_text' => 'course_type_text',
        ]);
    }

    /**
     * 关联课程学习记录
     */
    public function learnRecord(): HasOne
    {
        return $this->hasOne(LearnCourseRecord::class, 'course_id', 'course_id');
    }

}
